<template>
	<view>
		<view class="container">
			<!-- <view class="level-selector">
				<text>选择关卡：</text>
				<picker mode="selector" :range="levels" :value="level-1" @change="onLevelChange">
					<view class="picker">{{ level }}</view>
				</picker>
			</view>
			<view class="score-display">
				<text>当前得分：{{ score }}</text>
			</view> -->
			<view class="info">
				<text class="level">关卡: {{ level }}</text>
				<text class="score">得分: {{ score.toFixed(2) }}</text>
			</view>
			<view class="grid" :style="{ gridTemplateColumns: 'repeat(' + Math.sqrt(blocks.length) + ', 1fr)' }" v-if="blocks.length>0">
				<view v-for="block in blocks" :key="block.id" class="block" :style="{ backgroundColor: block.color, width:block.size,height:block.size}" @tap="blockTap(block.id)"></view>
			</view>
			<button @tap="startGame">开始游戏</button>
		</view>
	</view>


</template>

<script>
	export default {
		data () {
			return {
				blocks: [],
				activeBlocks: [],
				userChoices: [],
				level: 1,
				levels: Array.from({ length: 20 }, (_, i) => i + 1),
				numBlocksToShow: 3,
				score: 0,
				startTime: 0,
				// 初始行列数
				startRows: 4,
				// 色块显示时间
				showTime: 2000
			};
		},
		mounted () {
			this.generateBlocks(this.startRows)
		},
		computed: {
			blockStyle () {
				let rows = Math.sqrt(this.blocks.length)
				let size = 80 / rows + 'vw';
				uni.getSystemInfo({
					success: (res) => {
						const screenWidth = res.windowWidth; // 屏幕宽度，单位为px
						const screenHeight = res.windowHeight; // 屏幕高度，单位为px
						console.log('屏幕宽度：', screenWidth, rows);
						console.log('屏幕高度：', screenHeight);
						// 10为方块间间隔
						size = (screenWidth - rows * 10) / rows + 'px';
						return size
					}
				});
				// 根据宫格数量调整方块大小

			},
		},
		methods: {

			startGame () {
				this.initGame(); // 确保在组件加载完成后初始化游戏
			},
			async generateBlocks (num) {
				let size = 80 / num + 'vw';
				// 防止行列数过多超出，但一般达不到这种时候
				// await uni.getSystemInfo({
				//       success: (res) => {
				//         const screenWidth = res.windowWidth; // 屏幕宽度，单位为px
				//         const screenHeight = res.windowHeight; // 屏幕高度，单位为px
				//         console.log('屏幕宽度：', screenWidth,num);
				//         console.log('屏幕高度：', screenHeight);
				// 		// 10为方块间间隔
				// 		size=(screenWidth-num*10)/num+'px';
				//       }
				// });
				this.blocks = []
				Array.from({ length: Math.pow(num, 2) }, (_, i) => (i)).map((e, i) => {
					this.blocks.push({ id: i, color: '#cccccc', size: size })
				})
			},
			initGame () {
				this.activeBlocks = [];
				this.userChoices = [];
				this.showRandomBlocks(); // 显示随机色块
				this.startTime = new Date().getTime();
			},

			showRandomBlocks () {
				let blocksToShow = this.getBlocksToShow();
				this.blocks.forEach((block, index) => {
					block.color = blocksToShow.includes(index) ? this.getRandomColor() : '#cccccc';
				});
				this.activeBlocks = blocksToShow;

				// 设置2秒后将彩色块隐藏
				setTimeout(() => {
					this.blocks.forEach((block, index) => {
						if (blocksToShow.includes(index)) {
							block.color = '#cccccc';
						}
					});
				}, this.showTime); // 延迟2秒
			},

			blockTap (id) {
				if (!this.userChoices.includes(id)) {
					this.userChoices.push(id);
					this.blocks[id].color = '#3f85ed';
					if (this.userChoices.length === this.numBlocksToShow) {
						this.verifyChoices();
					}
				}
			},
			verifyChoices () {
				let isSuccess = this.userChoices.sort().toString() === this.activeBlocks.sort().toString();
				let timeTaken = new Date().getTime() - this.startTime;
				let timeBonus = Math.max(0, 100 - (timeTaken / 1000));
				this.blocks.forEach((block, index) => {
					block.color = this.activeBlocks.includes(index) ? (isSuccess ? '#5bc648' : '#ff5a5d') : '#cccccc';
				});

				if (isSuccess) {
					this.score += timeBonus;
					uni.showToast({
						title: `成功！得分：${timeBonus.toFixed(1)}`,
						icon: 'success',
						duration: 3000
					});
					setTimeout(() => {


						this.level++;
						// 每五关行列数加1
						if (this.level % 5 === 0) {
							this.generateBlocks(this.startRows + this.level / 5)
							// 每增加一次行列数色块显示时间加0.5s
							this.showTime += this.level / 5 * 500
						}
						this.numBlocksToShow = Math.min(this.level + 2, this.blocks.length);
						this.userChoices = [];
						this.initGame();
					}, 3000);
				} else {
					uni.showToast({
						title: '失败！请重试本关',
						icon: 'none',
						duration: 2000
					});

					setTimeout(() => {
						this.initGame();
					}, 3000);
				}
			},
			getBlocksToShow () {
				let blocksToShow = [];
				while (blocksToShow.length < this.numBlocksToShow) {
					let r = Math.floor(Math.random() * this.blocks.length);
					if (!blocksToShow.includes(r)) {
						blocksToShow.push(r);
					}
				}
				return blocksToShow;
			},
			getRandomColor () {
				const letters = '0123456789ABCDEF';
				let color = '#4dbbb8';
				// for (let i = 0; i < 6; i++) {
				//   color += letters[Math.floor(Math.random() * 16)];
				// }
				return color;
			},
			onLevelChange (event) {
				const selectedLevel = parseInt(event.target.value) + 1;
				this.level = selectedLevel;

				this.generateBlocks(this.startRows + Math.floor(this.level / 5))
				console.log("LENGTH", this.blocks);

				this.numBlocksToShow = Math.min(selectedLevel + 2, this.blocks.length);
				this.score = 0;
				this.initGame();
			}
		}
	};
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
		margin-top: 10vh;
	}

	.level-selector,
	.score-display {
		margin: 10px;
	}

	.picker {
		border: 1px solid #ddd;
		padding: 5px;
	}

	.grid {
		display: grid;
		/* grid-template-columns: repeat(5, 50px); */
		grid-gap: 10px;
		/* background-color: #cccccc; */
		padding: 10px;
	}

	.block {
		/* max-width: 50px;
		max-height: 50px;
		min-width: 30px;
		min-height: 30px; */
		transition: background-color 0.5s;
		border-radius: 6px;
	}



	.level,
	.score {
		font-size: 18px;
		color: #32cd32;
		/* Green */
	}
</style>